﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;

namespace Tk.Soc.Share.Common.Helpers
{
    public class JsonHelper
    {
        /// <summary>
        /// 将对象序列化为JSON格式
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>json字符串</returns>
        public static string SerializeObject(object o, bool _isFormat = false)
        {
            try
            {
                Formatting formatting = Formatting.None;
                if (_isFormat)
                {
                    formatting = Formatting.Indented;
                }
                string json = JsonConvert.SerializeObject(o, formatting);
                return json;
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("SerializeObject序列化异常" + ex);
                return "";
            }
        }

        /// <summary>
        /// 将对象序列化为JSON格式
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="dateformat"></param>
        /// <param name="_isFormat"></param>
        /// <returns></returns>
        public static string SerializeObjectDateTime(object o, string dateformat = "yyyy/MM/dd HH:mm:ss", bool _isFormat = false)
        {
            try
            {
                Formatting formatting = Formatting.None;
                if (_isFormat)
                {
                    formatting = Formatting.Indented;
                }
                string json = JsonConvert.SerializeObject(o, formatting, new IsoDateTimeConverter() { DateTimeFormat = dateformat });
                return json;
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("SerializeObject序列化异常" + ex);
                return "";
            }
        }


        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>json字符串</returns>
        public static T DeserializeObject<T>(string str, bool isConsole = true)
        {
            try
            {
                var net = JsonConvert.DeserializeObject<T>(str);
                return net;
            }
            catch (Exception ex)
            {
                if (isConsole)
                {
                    LogHelper.Logger.Error("SerializeObject反序列化异常  " + str + "    " + ex);
                }
                throw ex;
            }
        }
    }
}
